package cc.ttiot.thread.dataDumpThread;

import cc.ttiot.mapper.dao.ApproachingSwitchMsgMapper;
import cc.ttiot.mapper.dao.TemperatureAndHumidityMsgMapper;
import cc.ttiot.mapper.dao.VibrationMsgMapper;
import cc.ttiot.mapper.dao.WindPressureMsgMapper;
import cc.ttiot.mapper.domain.ApproachingSwitchMsg;
import cc.ttiot.mapper.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

/**
 * @Description: 数据库过期数据清理线程
 * @Author WangSuheng
 * @Date 2021/10/8 1:38
 * @Version 1.0
 */
public class DataDumpThread implements Runnable {
    //数据库初始化
    /*
         1) SqlSession类是线程不安全的，所以每个线程都要有个单独的SqlSession
         2) 下面这种sqlSessionFactory.openSession()的方式获取SqlSession对象默认事务autoCommit设为false，
            所以除了查询语句其他语句执行后要调用sqlSession.commit()方法提交事务
    */
    private final SqlSession sqlSession = MybatisUtils.getSqlSession();
    private final ApproachingSwitchMsgMapper asmMapper = sqlSession.getMapper(ApproachingSwitchMsgMapper.class);
    private final TemperatureAndHumidityMsgMapper tahmMapper = sqlSession.getMapper(TemperatureAndHumidityMsgMapper.class);
    private final VibrationMsgMapper vmMapper = sqlSession.getMapper(VibrationMsgMapper.class);
    private final WindPressureMsgMapper wpmMapper = sqlSession.getMapper(WindPressureMsgMapper.class);


    @Override
    public void run() {
        //每天(24h * 60min * 60s * 1000mills)清理一次
        while (true) {
            try {
                Thread.sleep( 60 * 60 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            asmMapper.deleteOneYearAgo();
            sqlSession.commit();

            tahmMapper.deleteOneMonthAgo();
            sqlSession.commit();

            vmMapper.deleteOneMonthAgo();
            sqlSession.commit();

            wpmMapper.deleteOneMonthAgo();
            sqlSession.commit();
        }
    }
}
